package com.ruoyi.shopping.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.huifu.adapay.model.PaymentReverse;
import com.ruoyi.adapayRecord.domain.AdapayRecord;
import com.ruoyi.adapayRecord.service.IAdapayRecordService;
import com.ruoyi.adapayRefund.domain.AdapayRefund;
import com.ruoyi.adapayRefund.service.IAdapayRefundService;
import com.ruoyi.common.constant.DicConstants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.order.domain.StoreProductOrder;
import com.ruoyi.shopping.domain.MallOrderMesh;
import com.ruoyi.shopping.service.IMallOrderMeshService;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.shopping.mapper.MallOrderMapper;
import com.ruoyi.shopping.domain.MallOrder;
import com.ruoyi.shopping.service.IMallOrderService;

/**
 * 商城订单Service业务层处理
 *
 * @author ruoyi
 * @date 2022-06-09
 */
@Service
public class MallOrderServiceImpl implements IMallOrderService
{
    @Autowired
    private MallOrderMapper mallOrderMapper;
    @Autowired
    private IAdapayRecordService adapayRecordService;
    @Autowired
    private IAdapayRefundService adapayRefundService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IMallOrderMeshService meshService;

    /**
     * 查询商城订单
     *
     * @param id 商城订单主键
     * @return 商城订单
     */
    @Override
    public MallOrder selectMallOrderById(Long id)
    {
        return mallOrderMapper.selectMallOrderById(id);
    }

    /**
     * 查询商城订单列表
     *
     * @param mallOrder 商城订单
     * @return 商城订单
     */
    @Override
    public List<MallOrder> selectMallOrderList(MallOrder mallOrder)
    {
        return mallOrderMapper.selectMallOrderList(mallOrder);
    }

    /**
     * 新增商城订单
     *
     * @param mallOrder 商城订单
     * @return 结果
     */
    @Override
    public int insertMallOrder(MallOrder mallOrder)
    {
        if(null==mallOrder.getDeductionPrice()){
            mallOrder.setDeductionPrice(new BigDecimal("0"));
        }
        mallOrder.setCreateTime(DateUtils.getNowDate());
        return mallOrderMapper.insertMallOrder(mallOrder);
    }

    /**
     * 修改商城订单
     *
     * @param mallOrder 商城订单
     * @return 结果
     */
    @Override
    public int updateMallOrder(MallOrder mallOrder)
    {
        mallOrder.setUpdateTime(DateUtils.getNowDate());
        return mallOrderMapper.updateMallOrder(mallOrder);
    }

    /**
     * 批量删除商城订单
     *
     * @param ids 需要删除的商城订单主键
     * @return 结果
     */
    @Override
    public int deleteMallOrderByIds(Long[] ids)
    {
        return mallOrderMapper.deleteMallOrderByIds(ids);
    }


    /**
     * 批量逻辑删除商城订单
     *
     * @param ids 需要删除的商城订单主键
     * @return 结果
     */
    @Override
    public int logicDeleteMallOrder(Long[] ids,String delType,Long delUser)
    {
        return mallOrderMapper.logicDeleteMallOrder(ids,delType,delUser);
    }

    /**
     * 删除商城订单信息
     *
     * @param id 商城订单主键
     * @return 结果
     */
    @Override
    public int deleteMallOrderById(Long id)
    {
        return mallOrderMapper.deleteMallOrderById(id);
    }

    @Override
    public void insrAll(ArrayList<MallOrder> needInsr) {
        for (MallOrder mallOrder : needInsr) {
            if(null==mallOrder.getDeductionPrice()){
                mallOrder.setDeductionPrice(new BigDecimal("0"));
            }
        }
        mallOrderMapper.insrAll(needInsr);
    }

    @Override
    public MallOrder selectByOrderId(String verifyCode) {
        return mallOrderMapper.selectByOrderId(verifyCode);
    }

    @Override
    public List<MallOrder> selectMallOrderByMeshId(Long id) {
        return mallOrderMapper.selectMallOrderByMeshId(id);
    }


    /**
     * 查询商城售后订单订单列表
     */
    @Override
    public List<MallOrder> selectAfterSaleOrderList(MallOrder mallOrder) {
        return mallOrderMapper.selectAfterSaleOrderList(mallOrder);
    }

    @Override
    public List<MallOrder> selectOrderList(MallOrder mallOrder) {
        return mallOrderMapper.selectOrderList(mallOrder);
    }

    @Override
    public List<MallOrder> selectNeedAutoConfirm(Integer day) {
        return mallOrderMapper.selectNeedAutoConfirm(day);
    }

    @Override
    public List<MallOrder> selectNeedFinished(Integer day) {
        return mallOrderMapper.selectNeedFinished(day);
    }

    @Override
    public AdapayRefund refundPay(Long orderId){
        MallOrder order = this.selectMallOrderById(orderId);
        if(null != order){
            if(!DicConstants.REFUND_STATUS_Pass.getCode().equals(order.getRefundStatus())) {
                //不处理
                return null;
            }
         /*
         这个是同步返回请求，不需要有退款中这个状态
          StoreProductOrder storeProductOrder=new StoreProductOrder();
            storeProductOrder.setId(orderId);
            storeProductOrder.setRefundPayStatus(DicConstants.REFUND_STATUS_Refunding.getCode());
            this.updateStoreProductOrder(storeProductOrder);*/
            MallOrderMesh mesh = meshService.selectMallOrderMeshById(order.getMergeOrderId());
            String payOrderNo=mesh.getPayOrderNo();
            if(null!=payOrderNo){

                AdapayRecord adapayRecordQuery=new AdapayRecord();
                adapayRecordQuery.setPayOrderId(payOrderNo);
                adapayRecordQuery.setBelongType("mall");
                List<AdapayRecord>  list=adapayRecordService.selectAdapayRecordList(adapayRecordQuery);
                if(list.size()>0){
                    //找到了支付记录
                    AdapayRecord adapayRecord= list.get(0);
                    String paymentId= adapayRecord.getPaymentId();
                    String notifyParam=adapayRecord.getNotifyParam();
                    //从通知里面获取真实支付金额进行退款
//                    JSONObject notifyParamJSon= JSONObject.parseObject(notifyParam);
//                    String pay_amt=notifyParamJSon.getString("pay_amt");
                    String pay_amt=order.getPayPrice().toString();
//                    Map<String, Object> refundParams = new HashMap<String, Object>();
                 /*   String refund_order_no="refund" + System.currentTimeMillis();
                    refundParams.put("refund_amt", pay_amt);
                    refundParams.put("refund_order_no", refund_order_no);*/
                    String refund_order_no="refund" + System.currentTimeMillis();
                    String domain=configService.selectConfigByKey("domain");
                    String notify_url=domain+"/prod-api/client/mall/order/refundPayNotify";
                    /*refundParams.put("notify_url", notify_url);*/
                    String app_id=configService.selectConfigByKey("adpay_app_id");
                    Map<String, Object> reverseParams = new HashMap<>();
                    reverseParams.put("app_id", app_id);
                    reverseParams.put("payment_id",paymentId);
                    reverseParams.put("reverse_amt", pay_amt);
                    reverseParams.put("notify_url", notify_url);
                    reverseParams.put("order_no", refund_order_no);

                    AdapayRefund adapayRefund=new AdapayRefund();
                    adapayRefund.setRefundOrderNo(refund_order_no);
                    adapayRefund.setPaymentId(paymentId);
                    adapayRefund.setProductOrderId(orderId);
                    adapayRefund.setReqState(DicConstants.SYS_Y.getCode());
                    adapayRefund.setReqParam(reverseParams.toString());
                    Map<String, Object> paymentReverse =null;
                    try{
                        paymentReverse=  PaymentReverse.create(reverseParams);
                    }catch (Exception e){
                        e.printStackTrace();
                        adapayRefund.setReqState(DicConstants.SYS_N.getCode());
                        adapayRefund.setReqFailMsg(e.getMessage());
                        adapayRefundService.insertAdapayRefund(adapayRefund);
                        return adapayRefund;
                    }

                    adapayRefund.setResParam(paymentReverse.toString());
                    String error_code = (String) paymentReverse.get("error_code");
                    if (null != error_code) {
                        String error_msg = (String) paymentReverse.get("error_msg");
                        System.out.println("error_code:" + error_code + "............." + error_msg);
                        adapayRefund.setReqState(DicConstants.SYS_N.getCode());
                        adapayRefund.setReqFailMsg(error_msg);
                        adapayRefundService.insertAdapayRefund(adapayRefund);
                        return adapayRefund;
                    }
                    order.setRefundMoney(order.getPayPrice());
                    order.setRefundPayOrderNo(refund_order_no);
                    order.setRefundStatus(DicConstants.REFUND_STATUS_Finished.getCode());
                    this.updateMallOrder(order);
                    List<MallOrder> orders = this.selectMallOrderByMeshId(order.getMergeOrderId());
                    int count = 0;
                    for (MallOrder o : orders) {
                        if(DicConstants.REFUND_STATUS_Finished.getCode().equals(o.getRefundStatus())){
                            count++;
                        }
                    }
                    if(count == orders.size()){
                        mesh.setAftersaleState(DicConstants.SYS_Y.getCode());
                        mesh.setOrderState(DicConstants.ORDER_STATE_FINISHED.getCode());
                        meshService.updateMallOrderMesh(mesh);
                    }
                    adapayRefundService.insertAdapayRefund(adapayRefund);
                    return adapayRefund;
                }
            }
        }
        return null;
    }

    @Override
    public void refund(MallOrder order, AdapayRefund adapayRefund) {
        if(null==adapayRefund){
            return;
        }
        if(DicConstants.SYS_Y.getCode().equals(adapayRefund.getReqState())){
            //退款发起成功,具体结果等待回调
            order.setRefundStatus(DicConstants.REFUND_STATUS_Finished.getCode());
            order.setRefundPayOrderNo(adapayRefund.getRefundOrderNo());
//            order.setRefundPrice(order.getPayPrice());
        }else{
            //失败
            order.setRefundStatus(DicConstants.REFUND_STATUS_Refused.getCode());
            order.setRefundPayErrMsg(adapayRefund.getReqFailMsg());
        }
        this.updateMallOrder(order);
    }

    @Override
    public void checkFinished(Long meshId) {
        List<MallOrder> orders = this.selectMallOrderByMeshId(meshId);
        int count = 0;
        for (MallOrder order : orders) {
            if (DicConstants.REFUND_STATUS_Finished.getCode().equals(order.getAfterSalesState()) || DicConstants.SYS_Y.getCode().equals(order.getCommentStatus())) {
                count++;
            }
        }
        if (count >= orders.size()) {
            MallOrderMesh mallOrderMesh = meshService.selectMallOrderMeshById(meshId);
            mallOrderMesh.setOrderState(DicConstants.ORDER_STATE_FINISHED.getCode());
            meshService.updateMallOrderMesh(mallOrderMesh);
        }
    }
}
